<template>
  <div v-if="className" :class="className">
    <div :id="id" :style="{height:height,width:width}" />
  </div>
  <div v-else :id="id" :style="{height:height,width:width}" />
</template>

<script>
import echarts from 'echarts'
import resize from './mixins/resize'

export default {
  name: 'Echarts',
  mixins: [resize],
  props: {
    className: {
      type: String,
      default: ''
    },
    id: {
      type: String,
      default: () => { return Math.random().toString(36).substr(2) }
    },
    width: {
      type: String,
      default: '100%'
    },
    height: {
      type: String,
      default: '100%'
    },
    option: {
      type: Object,
      default: () => {
        return {
          title: {
            left: 'center',
            text: '默认图表'
          },
          xAxis: {
            type: 'category',
            data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
          },
          yAxis: {
            type: 'value'
          },
          series: [{
            data: [820, 932, 901, 934, 1290, 1330, 1320],
            type: 'line'
          }]
        }
      }
    }
  },
  data() {
    return {
      chartInstance: null
    }
  },
  watch: {
    option: {
      handler: function(newValue, oldValue) {
        this.chartInstance.setOption(newValue)
      },
      deep: true
    }
  },
  mounted() {
    this.initChart()
  },
  beforeDestroy() {
    if (!this.chartInstance) {
      return
    }
    this.chartInstance.dispose()
    this.chartInstance = null
  },
  created() {
  },
  methods: {
    initChart() {
      this.chartInstance = echarts.init(document.getElementById(this.id))
      this.chartInstance.setOption(this.option)
    },
    setOption(option, ...argv) {
      this.chartInstance.setOption(option, ...argv)
    }
  }
}
</script>
